﻿using XiaoMan.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
//using Microsoft.Office.Interop.Excel;
using System.IO;
using Aspose.Cells;
using System.Data;
using System.Reflection;


namespace BLL
{
    public class BaseService<T> where T : class
    {
        public BaseDAO<T> currentDAO = new DAL.BaseDAO<T>();
        public bool Add(T entity)
        {
            currentDAO.Add(entity);
            return DbContextFactory.SaveChanges() > 0;
        }
        public bool Delete(T entity)
        {
            currentDAO.Delete(entity);
            return DbContextFactory.SaveChanges() > 0;
        }
        public bool Update(T entity)
        {
            currentDAO.Update(entity);
            return DbContextFactory.SaveChanges() > 0;
        }
        public List<T> GetList(Func<T, bool> where)
        {
            return currentDAO.GetList(where);
        }
        public List<T> GetListOrdeyByPage<S>(Func<T, bool> lambadaWhere, Func<T, S> lambadaOrdey, bool isAsc, int pageIndex, int pageSize, ref int Count)
        {
            return currentDAO.GetListOrdeyByPage(lambadaWhere, lambadaOrdey, isAsc, pageIndex, pageSize, ref Count);
        }

        // mxj 2016.10.19 从数据导出到excel的通用函数
        //public bool ExportDataToExcel(string sTitle, System.Data.DataTable dt, string filePath)
        //{
        //    object missing = System.Reflection.Missing.Value;
        //    Application excel = new Application();
        //    if (excel == null)
        //    {
        //        return false;
        //    }

        //    try
        //    {
        //        excel.Visible = false;
        //        //新建EXCEL文件
        //        Workbook wb = excel.Workbooks.Add(missing);
        //        //取得第一个工作薄
        //        Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);

        //        int colCount = dt.Columns.Count;

        //        //操作大标题
        //        ws.Cells[1, 1] = sTitle;
        //        Range rtemp = ws.get_Range((object)ws.Cells[1, 1], (object)ws.Cells[1, colCount]);
        //        rtemp.Merge(missing);
        //        rtemp.HorizontalAlignment = XlVAlign.xlVAlignCenter;
        //        rtemp.Font.FontStyle = "加粗";
        //        rtemp.Font.Size = 14;

        //        //操作表格标题
        //        for (int i = 0; i < colCount; i++)
        //        {
        //            ws.Cells[2, i + 1] = dt.Columns[i].ColumnName;
        //        }
        //        rtemp = ws.get_Range((object)ws.Cells[2, 1], (object)ws.Cells[2, colCount]);
        //        rtemp.HorizontalAlignment = XlVAlign.xlVAlignCenter;
        //        rtemp.Font.FontStyle = "加粗";

        //        //设置为表格文本格式
        //        rtemp = ws.get_Range((object)ws.Cells[2, 1], (object)ws.Cells[dt.Rows.Count + 2, colCount]);
        //        rtemp.NumberFormatLocal = "@";

        //        //操作内容
        //        int currentRow = 2;  // 当前操作的行数
        //        foreach (System.Data.DataRow r in dt.Rows)
        //        {
        //            currentRow++;  // excel表格中具体的内容从2开始
        //            for(int i=0;i<colCount;i++)
        //            {
        //                ws.Cells[currentRow, i+1] = r[i].ToString();  
        //            }
        //        }

        //        if (dt.Rows.Count > 0)
        //        {
        //            rtemp = ws.get_Range((object)ws.Cells[2, 1], (object)ws.Cells[dt.Rows.Count + 2, colCount]);
        //            //自动适应宽度
        //            rtemp.Columns.AutoFit();

        //            //内容加上边框
        //            rtemp.Borders.LineStyle = XlLineStyle.xlContinuous;
        //            rtemp.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThin;
        //            rtemp.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThin;
        //            rtemp.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThin;
        //            rtemp.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
        //        }

        //        //excel.Visible = true;

        //        ws.SaveAs(filePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
        //        excel.Quit();
        //        excel = null;
        //        killProc();
        //        return true;
        //    }
        //    catch
        //    {
        //        excel.Quit();
        //        excel = null;
        //        killProc();
        //        return false;
        //    }
        //}

        //public void killProc()
        //{
        //    System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
        //    foreach (System.Diagnostics.Process p in process)
        //    {
        //        if (!string.IsNullOrEmpty(p.ProcessName))
        //        {
        //            try
        //            {
        //                p.Kill();
        //            }
        //            catch { }
        //        }
        //    }

        //}

        void setColumnWithAuto(Worksheet sheet)
        {
            Cells cells = sheet.Cells;
            int columnCount = cells.MaxColumn;  //获取表页的最大列数
            int rowCount = cells.MaxRow;        //获取表页的最大行数

            for (int col = 0; col < columnCount; col++)
            {
                sheet.AutoFitColumn(col, 0, rowCount);
            }
            for (int col = 0; col < columnCount; col++)
            {
                cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);
            }
        }


        //zsf导出
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ReportTitleName">表格名称</param>
        /// <param name="list">数据源</param>
        /// <param name="filePath">储存路径（绝对路径）</param>
        /// <param name="IsColumn">是否显示Datatable中的Column</param>
        /// <returns></returns>
        public bool DatabseToExcel(string ReportTitleName, DataTable list, string filePath, int IsColumn)
        {
            try
            {
                //获取用户选择的excel文件名称
                string path;
                //获取保存路径
                //path = System.Windows.Forms.Application.StartupPath + @"\Excel\" + ReportTitleName + ".xls";
                path = filePath;
                Workbook wb = new Workbook();
                Worksheet ws = wb.Worksheets[0];
                Cells cell = ws.Cells;
                //定义并获取导出的数据源
                string[,] _ReportDt = new string[list.Rows.Count, list.Columns.Count];
                for (int i = 0; i < list.Rows.Count; i++)
                {
                    for (int j = 0; j < list.Columns.Count; j++)
                    {
                        _ReportDt[i, j] = list.Rows[i][j].ToString();
                    }
                }
                //合并第一行单元格
                Range range = cell.CreateRange(0, 0, 1, list.Columns.Count);
                range.Merge();
                cell["A1"].PutValue(ReportTitleName); //标题

                //设置行高
                cell.SetRowHeight(0, 20);

                //设置字体样式
                Style style1 = wb.Styles[wb.Styles.Add()];
                style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
                style1.Font.Name = "宋体";
                style1.Font.IsBold = true;//设置粗体
                style1.Font.Size = 12;//设置字体大小

                Style style2 = wb.Styles[wb.Styles.Add()];
                style2.HorizontalAlignment = TextAlignmentType.Center;
                style2.Font.Size = 10;

                //给单元格关联样式
                cell["A1"].SetStyle(style1); //报表名字 样式

                //设置Execl列名
                int posStart = 0;
                if (IsColumn == 1)
                {
                    for (int i = 0; i < list.Columns.Count; i++)
                    {
                        cell[1, i].PutValue(list.Columns[i].ColumnName);
                        cell[1, i].SetStyle(style2);
                    }

                    posStart = 2;
                }
                else
                {
                    posStart = 1;
                }
                //设置单元格内容
                for (int i = 0; i < list.Rows.Count; i++)
                {
                    for (int j = 0; j < list.Columns.Count; j++)
                    {
                        cell[i + posStart, j].PutValue(_ReportDt[i, j].ToString());
                        cell[i + posStart, j].SetStyle(style2);
                    }
                }
                //自适应宽度
                setColumnWithAuto(ws);
                wb.Save(path);

                return true;
            }
            catch (Exception)
            {

                return false;
            }

        }

        /// <summary>
        /// 把对象里的null变成相应类型的默认值
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        public T WipeNull(T entity)
        {
            System.Reflection.PropertyInfo[] ps = entity.GetType().GetProperties();
            Type type = entity.GetType();
            foreach (PropertyInfo propertie in ps)
            {
                if (propertie.PropertyType == typeof(string))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, "", null);
                    }
                }
                else if (propertie.PropertyType == typeof(Int32))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, 0, null);
                    }
                }
                else if (propertie.PropertyType == typeof(Nullable<int>))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, 0, null);
                    }
                }
                else if (propertie.PropertyType == typeof(decimal))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null);
                    }
                }
                else if (propertie.PropertyType == typeof(Nullable<decimal>))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null);
                    }
                }
            }
            return entity;
        }

    }
}
